#include "usersql.h"

UserSql::UserSql(QWidget *parent) : QWidget(parent)
{
    init();  // 构造时初始化数据库
}

UserSql::~UserSql()
{
    if (m_db.isOpen()) {
        m_db.close();
    }
}

void UserSql::init()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName("127.0.0.1");
    m_db.setDatabaseName("test");  // MySQL 中的数据库名称
    m_db.setPort(3306);
    m_db.setUserName("root");
    m_db.setPassword("12345678");

    if (!m_db.open()) {
        QMessageBox::critical(this, "数据库连接失败", m_db.lastError().text());
    } else {
        qDebug() << "数据库连接成功";
    }
}

bool UserSql::checkUserPassword(const QString &username, const QString &password)
{
    QSqlQuery query;
    query.prepare("SELECT password FROM users WHERE username = :username");
    query.bindValue(":username", username);

    if (query.exec() && query.next()) {
        QString dbPassword = query.value(0).toString();
        return dbPassword == password;
    } else {
        return false;
    }
}
